package com.eastfair.imaster.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastfair.config.api.ConfigServiceFeign;
import com.eastfair.config.dto.AttachmentDTO;
import com.eastfair.constant.AttachmentType;
import com.eastfair.enums.BusinessTypeEnum;
import com.eastfair.enums.FileTypeEnum;
import com.eastfair.imaster.service.SelfAttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * Date:2021/9/6
 * Time:14:26
 *
 * @author zjn
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class SelfAttachmentServiceImpl implements SelfAttachmentService {

    @Autowired
    private ConfigServiceFeign configServiceFeign;

    @Override
    public Boolean saveAttachments(List<AttachmentDTO> attachmentDTOList, BusinessTypeEnum businessType, Long businessId) {
        return configServiceFeign.saveAttachmentList(convertAttachments(attachmentDTOList, businessType, businessId)).getData();
    }

    @Override
    public List<AttachmentDTO> convertAttachments(List<AttachmentDTO> attachmentDTOList, BusinessTypeEnum businessType, Long businessId) {
        if (attachmentDTOList == null || attachmentDTOList.isEmpty()) {
            throw new RuntimeException("error param, attachmentDTOList is empty");
        }
        if (businessType == null) {
            throw new RuntimeException("error param, businessType is null");
        }
        if (businessId == null) {
            throw new RuntimeException("error param, businessId is null");
        }

        for (int i = 0; i < attachmentDTOList.size(); i++) {
            //获取文件类型
            FileTypeEnum fileTypeEnum = getFileTypeEnum(attachmentDTOList.get(i).getFileUrl());
            if (!Objects.isNull(fileTypeEnum)) {
                attachmentDTOList.get(i).setFileType(fileTypeEnum.name());
            }

            attachmentDTOList.get(i).setBusinessType(businessType.name());
            attachmentDTOList.get(i).setBusinessId(businessId);
        }
        return attachmentDTOList;
    }

    /**
     * 获取文件类型
     *
     * @param fileUrl 文件url
     * @return 文件类型
     */
    private FileTypeEnum getFileTypeEnum(String fileUrl) {
        int index = fileUrl.lastIndexOf(AttachmentType.STR_POINT);
        String fileType = fileUrl.substring(index + 1);
        return FileTypeEnum.get(fileType);
    }

}
